package cn.com.blueInfo.security.filter;

import cn.com.blueInfo.core.entity.CurrentLoginUserInfo;
import cn.com.blueInfo.core.param.SecurityParam;
import cn.com.blueInfo.core.util.JwtUtils;
import cn.com.blueInfo.security.service.JwtAuthenticationEntryPoint;
import cn.com.blueInfo.utils.error.JwtAuthenticationException;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SecurityAuthenticationFilter extends OncePerRequestFilter {

    private final AuthenticationEntryPoint authenticationEntryPoint = new JwtAuthenticationEntryPoint();

    private final JwtUtils jwtUtils;

    private final CurrentLoginUserInfo currentLoginUserInfo;

    private final SecurityParam securityParam;

    public SecurityAuthenticationFilter(JwtUtils jwtUtils, CurrentLoginUserInfo currentLoginUserInfo, SecurityParam securityParam) {
        this.jwtUtils = jwtUtils;
        this.currentLoginUserInfo = currentLoginUserInfo;
        this.securityParam = securityParam;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            if (this.securityParam.isSecuritySwitch()) {
                String token = getJwtFromRequest(request);
                if (StringUtils.isNotBlank(token)) {
                    if (validateToken(token)) {
                        String username = getUsernameFromToken(token);

                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                username, null, null);
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
            filterChain.doFilter(request, response);
        } catch (JwtAuthenticationException e) {
            // 验证失败，清除安全上下文
            SecurityContextHolder.clearContext();
            authenticationEntryPoint.commence(request, response, e);
        } catch (Exception e) {
            logger.error("Failed to process authentication", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
        }
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    private boolean validateToken(String token) {
        Claims claims = null;
        try {
            claims = jwtUtils.parseToken(token);
            setCommonUserInfo(claims);
            return true;
        } catch (JwtAuthenticationException e) {
            throw new JwtAuthenticationException(e.getMessage(), e);
        }
    }

    private void setCommonUserInfo(Claims claims) {
        String loginName = claims.getSubject();
        String tenantId = claims.get("tenantId", String.class);
        String applicationId = claims.get("applicationId", String.class);
        String userId = claims.get("userId", String.class);
        currentLoginUserInfo.setLoginName(loginName);
        currentLoginUserInfo.setTenantId(Long.valueOf(tenantId));
        currentLoginUserInfo.setApplicationId(Long.valueOf(applicationId));
        currentLoginUserInfo.setUserId(Long.valueOf(userId));
    }

    private String getUsernameFromToken(String token) {
        // 从 JWT 中获取用户名
        return jwtUtils.getUsernameFromToken(token);
    }
}
